var express = require('express');
var router = express.Router();

/* GET home page. */
router
	.get('/', function(req, res, next) {
		res.render("register");
	})
	.post('/', function(req, res, next) {

		var response;

		var mysql      = require('mysql');
		var connection = mysql.createConnection({
							    host     : 'localhost',
							    user     : 'root',
							    password : 'root',
							    database : 'jingsai'
							});

		connection.connect();

		connection.query('SELECT USERNAME, PASSWORD FROM USERS ' +
		    "WHERE USERNAME='"+req.body.username+"'", function (error, data) {
		    if (error) throw error;
		    if(data.length>0){
				response = {
					"status":"failed"
				}
				console.log('注册失败，注册用户名为：'+req.body.username);
		    	res.json(response);
		    }else{
		    	connection.query('INSERT INTO USERS SET ?',{username: req.body.username, password:req.body.password},function(error,data){
					response = {
						"status":"success"
					}
					console.log('注册成功，注册用户名为：'+req.body.username);
					res.json(response);
		    	})
		    }
		  });
	});;

module.exports = router;
